package com.ruoyi.crm.service.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.constant.CrmConstant;
import com.ruoyi.common.core.domain.entity.SysCity;
import com.ruoyi.common.enums.erp.CrmCustomerIndustryEnum;
import com.ruoyi.common.enums.erp.CrmCustomerRankEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.crm.domain.dto.CrmCustomerTraceDTO;
import com.ruoyi.crm.domain.dto.CrmCustomerUserDTO;
import com.ruoyi.crm.domain.dto.CrmOrderDTO;
import com.ruoyi.crm.service.ICrmOrderService;
import com.ruoyi.system.mapper.SysCityMapper;
import com.taobao.api.ApiException;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.crm.mapper.CrmCustomerMapper;
import com.ruoyi.crm.domain.CrmCustomer;
import com.ruoyi.crm.service.ICrmCustomerService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 客户列Service业务层处理
 *
 * @author yanwenliang
 * @date 2024-10-18
 */
@Service
public class CrmCustomerServiceImpl extends ServiceImpl<CrmCustomerMapper, CrmCustomer> implements ICrmCustomerService {
    @Autowired
    private CrmCustomerMapper crmCustomerMapper;


    @Autowired
    private ICrmOrderService crmOrderService;

    /**
     * 查询客户列
     *
     * @param customerId 客户列主键
     * @return 客户列
     */
    @Override
    public CrmCustomer selectCrmCustomerByCustomerId(String customerId) {
        return crmCustomerMapper.selectCrmCustomerByCustomerId(customerId);
    }

    /**
     * 查询客户列列表
     *
     * @param crmCustomer 客户列
     * @return 客户列
     */
    @Override
    public List<CrmCustomer> selectCrmCustomerList(CrmCustomer crmCustomer) {
        List<CrmCustomer> crmCustomers = crmCustomerMapper.selectCrmCustomerList(crmCustomer);

        crmCustomers.forEach(customer -> {
            List<CrmOrderDTO> crmOrderDTO = crmOrderService.getCrmOrderDTO(customer.getCustomerId());
            customer.setOrderList(crmOrderDTO);
        });

        this.buildGroupCrmCustomer(crmCustomers);

        return crmCustomers;
    }

    // 按商机进度分组以及计算总金额
    private void buildGroupCrmCustomer(List<CrmCustomer> crmCustomers){
        crmCustomers.forEach(customer -> {
            List<CrmOrderDTO> orderList = customer.getOrderList();

            Map<String, List<CrmOrderDTO>> map = new HashMap<>();
            BigDecimal orderCountAmt = BigDecimal.ZERO;

            for (CrmOrderDTO order : orderList) {
                String key = "other";
                if ("2".equals(order.getProgess())) key = "progess30";
                if ("3".equals(order.getProgess())) key = "progess60";
                if ("4".equals(order.getProgess())) key = "progess90";

                map.computeIfAbsent(key, k -> new ArrayList<>()).add(order);
                orderCountAmt = orderCountAmt.add((ObjectUtils.isEmpty(order.getAmount()) || !"5".equals(order.getProgess())) ? BigDecimal.ZERO : order.getAmount());
            }

            customer.setOrderCountAmt(orderCountAmt);
            customer.setOrderDTOMap(map);
        });
    }


    /**
     * 新增客户列
     *
     * @param crmCustomer 客户列
     * @return 结果
     */
    @Override
    public int insertCrmCustomer(CrmCustomer crmCustomer){

        Integer integer = baseMapper.selectCount(new LambdaQueryWrapper<CrmCustomer>().eq(CrmCustomer::getCustomerName, crmCustomer.getCustomerName()));

        if (integer > 0) {
            throw new ServiceException("该客户已经存在，无法创建");
        }

        crmCustomer.setCreateTime(DateUtils.getNowDate());
        crmCustomer.setCreateBy(SecurityUtils.getUsername());
        crmCustomer.setCustomerId(IdWorker.getIdStr());
        crmCustomer.setUserId(SecurityUtils.getUserId());

//        this.setRegions(crmCustomer);

        int i = crmCustomerMapper.insertCrmCustomer(crmCustomer);
        if (i > 0) {
            OapiRobotSendRequest.Markdown msg = this.createMsg(crmCustomer, "客户新建通知");
            MessageUtil.sendGroup(msg, DDConstant.SECRET_INFO, DDConstant.CUSTOM_ROBOT_TOKEN_INFO);
        }


        return i;
    }


    /**
     * 组装群消息
     * @param crmCustomer
     * @return
     */
    private OapiRobotSendRequest.Markdown createMsg(CrmCustomer crmCustomer, String title){
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(title);
        StringBuilder text = new StringBuilder();
        text.append("## **" + title + "**");
        text.append("  \n  ");
        text.append("客户名称：" + crmCustomer.getCustomerName());
        text.append("  \n  ");
        text.append("所属地区：" + crmCustomer.getRegion());
        text.append("  \n  ");
        text.append("客户级别：" + CrmCustomerRankEnum.getInfo(crmCustomer.getCustomerRank()));
        text.append("  \n  ");
        text.append("客户行业：" + CrmCustomerIndustryEnum.getInfo(crmCustomer.getCustomerIndustry()));
        text.append("  \n  ");
        text.append("负责人：" + crmCustomer.getCreateBy());
        markdown.setText(text.toString());

        return markdown;
    }


//    private void setRegions(CrmCustomer crmCustomer) {
//        String[] cityIds = crmCustomer.getRegionId().split(",");
//        ArrayList<String> regions = new ArrayList<>();
//
//        for (String cityId : cityIds) {
//            SysCity sysCity = cityMapper.getCityByCityId(Long.parseLong(cityId));
//            regions.add(sysCity.getCityName());
//        }
//
//        crmCustomer.setRegion(String.join(",", regions));
//    }

    /**
     * 修改客户列
     *
     * @param crmCustomer 客户列
     * @return 结果
     */
    @Override
    public int updateCrmCustomer(CrmCustomer crmCustomer) {
        crmCustomer.setUpdateTime(DateUtils.getNowDate());
        crmCustomer.setUpdateBy(SecurityUtils.getUsername());

        // 如果是数字事业部的客户则发送通知
        int i = crmCustomerMapper.updateCrmCustomer(crmCustomer);
        if (i > 0) {
            OapiRobotSendRequest.Markdown msg = this.createMsg(crmCustomer, "客户修改通知");
            MessageUtil.sendGroup(msg, DDConstant.SECRET_INFO, DDConstant.CUSTOM_ROBOT_TOKEN_INFO);
        }
        return i;
    }

    /**
     * 批量删除客户列
     *
     * @param customerIds 需要删除的客户列主键
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerByCustomerIds(String[] customerIds) {
        return crmCustomerMapper.deleteCrmCustomerByCustomerIds(customerIds);
    }

    /**
     * 删除客户列信息
     *
     * @param customerId 客户列主键
     * @return 结果
     */
    @Override
    public int deleteCrmCustomerByCustomerId(String customerId) {
        return crmCustomerMapper.deleteCrmCustomerByCustomerId(customerId);
    }

    /**
     * 查询核心客户列列表
     * @param crmCustomer
     * @return
     */
    @Override
    public List<CrmCustomer> getMyCustomerList(CrmCustomer crmCustomer) {
        crmCustomer.setUserId(SecurityUtils.getUserId());
        List<CrmCustomer> myCustomerList = crmCustomerMapper.getMyCustomerList(crmCustomer);
        myCustomerList.forEach(customer -> {
            List<CrmOrderDTO> crmOrderDTO = crmOrderService.getCrmOrderDTO(customer.getCustomerId());
            customer.setOrderList(crmOrderDTO);
        });
        this.buildGroupCrmCustomer(myCustomerList);
        return myCustomerList;
    }


    /**
     * 查询选择的核心客户列列表
     * @param crmCustomer
     * @return
     */
    @Override
    public List<CrmCustomer> getChooseCustomerList(CrmCustomer crmCustomer) {
        return crmCustomerMapper.getChooseCustomerList(crmCustomer);
    }

    /**
     * 选择核心客户列列表
     * @param crmCustomer
     * @return
     */
    @Override
    public int chooseCustomer(CrmCustomer crmCustomer) {

        CrmCustomer customer = baseMapper.selectById(crmCustomer.getCustomerId());

        if (ObjectUtils.isEmpty(customer)){
            throw new ServiceException("当前客户不存在，请刷新页面后重试");
        }

        CrmCustomerUserDTO crmCustomerUserDTO = new CrmCustomerUserDTO();

        crmCustomerUserDTO.setCustomerUserId(IdWorker.getIdStr());
        crmCustomerUserDTO.setUserId(SecurityUtils.getUserId());
        crmCustomerUserDTO.setCustomerId(crmCustomer.getCustomerId());
        return crmCustomerMapper.chooseCustomer(crmCustomerUserDTO);
    }

    /**
     * 添加跟进记录
     * @param crmCustomerTraceDTO
     * @return
     */
    @Override
    @Transactional
    public int addCrmCustomerTrace(CrmCustomerTraceDTO crmCustomerTraceDTO) {

        CrmCustomer customer = baseMapper.selectById(crmCustomerTraceDTO.getCustomerId());

        if (ObjectUtils.isEmpty(customer)){
            throw new ServiceException("客户不存在，请刷新页面后重试！");
        }

        crmCustomerTraceDTO.setTraceCustomerBy(SecurityUtils.getUsername());
        crmCustomerTraceDTO.setTraceCustomerTime(new Date());
        crmCustomerTraceDTO.setTraceCustomerId(IdWorker.getIdStr());

        customer.setLastUpdateRecord(crmCustomerTraceDTO.getTraceCustomerContent());
        customer.setLastFollowupTime(new Date());
        customer.setNextFollowupTime(crmCustomerTraceDTO.getTraceCustomerNextTime());

        baseMapper.updateById(customer);

        return baseMapper.addCrmCustomerTrace(crmCustomerTraceDTO);
    }

    @Override
    public List<CrmCustomer> getList(CrmCustomer crmCustomer) {
        return baseMapper.getList(crmCustomer);
    }
}
